package com.bum.api.core.util.render;

import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang.time.FastDateFormat;

public class TimeAgo {
	static final String AGO 	= " trước";
	static final String SECONDS = "%d giây";
	static final String MINUTE 	= "khoảng 1 phút" + AGO;
	static final String MINUTES = "%d phút";
	static final String HOUR 	= "khoảng 1 giờ" + AGO;
	static final String HOURS 	= "khoảng %d giờ";
	static final String DAY 	= "1 ngày" + AGO;
	static final String DAYS 	= "%d ngày";
	static final String MONTH 	= "khoảng 1 tháng";
	static final String MONTHS 	= "%d tháng";
	static final String YEAR 	= "khoảng 1 năm" + AGO;
	static final String YEARS 	= "%d năm";
	
	static String fillNumber(String text, Number number) {
		return text.replace("%d", number.toString()) + AGO;
	}
	
	public static String getTimeAgo(long time) {
		long amount = System.currentTimeMillis() - time;
		amount = Math.abs(amount);
		
		/**
		 * seconds
		 */
		amount = amount / 1000;
		if (amount == 0) {
			return "vừa tức thì";
		}
		
		if (amount < 45) {
			return fillNumber(SECONDS, amount);
		}
		if (amount < 90) {
			return MINUTE;
		}
		
		/**
		 * minutes
		 */
		amount = amount / 60;
		if (amount < 45) {
			return fillNumber(MINUTES, amount);
		}
		if (amount < 90) {
			return HOUR;
		}
		
		/**
		 * hours
		 */
		amount = amount / 60;
		if (amount < 24) {
			return fillNumber(HOURS, amount);
		}
		if (amount < 48) {
			return DAY;
		}
		
		/**
		 * days
		 */
		amount = amount / 24;
		if (amount < 30) {
			return fillNumber(DAYS, amount);
		}
		if (amount < 60) {
			return MONTH;
		}
		if (amount < 365) {
			return fillNumber(MONTHS, amount / 30);
		}
		
		/**
		 * years
		 */
		amount = amount /365;
		if (amount < 2) {
			return YEAR;
		}
		return fillNumber(YEARS, amount);
	}
	
	
//	private static final ThreadLocal<DateFormat> dmy = new ThreadLocal<DateFormat>() {
//		protected DateFormat initialValue() {
//			return new SimpleDateFormat("dd/MM/yyyy");
//		}
//	};
	public static String getDMy(long time) {
//		return dmy.get().format(new Date(time));
		return FastDateFormat.getInstance("dd/MM/yyyy").format(new Date(time));
	}
	
//	private static final ThreadLocal<DateFormat> tl = new ThreadLocal<DateFormat>() {
//		protected DateFormat initialValue() {
//			return new SimpleDateFormat("EEEEE, dd/MM/yyyy HH:mm:ss", new Locale("vi", "VI"));
//		}
//	};
	public static String getDateString(long time) {
//	    return tl.get().format(new Date(time));
		return FastDateFormat.getInstance("EEEEE, dd/MM/yyyy HH:mm:ss", new Locale("vi", "VI")).format(new Date(time));
	}
}
